package org.meeting.radish.controller;

import lombok.extern.slf4j.Slf4j;
import org.meeting.radish.entity.User;
import org.meeting.radish.service.UserService;
import org.meeting.radish.util.CookieUtil;
import org.meeting.radish.util.EncodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Slf4j
@Controller
public class LoginController {

    @Resource
    UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(User user, HttpServletResponse resp) throws NoSuchAlgorithmException {
        EncodeUtil.userPasswordEncode(user);
        User queryUser = userService.queryUser(user);
        if (queryUser == null) {
            return "redirect:/login";
        }
        CookieUtil.addCookie("uid", String.valueOf(queryUser.getUid()), resp);
        CookieUtil.addCookie("username", queryUser.getUsername(), resp);
        CookieUtil.addCookie("status", String.valueOf(queryUser.getStatus()), resp);
        log.info("{}|login", queryUser);
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        req.getSession().invalidate();
        CookieUtil.deleteCookie(resp, req.getCookies());
        return "redirect:/login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String register(User user, RedirectAttributes redirect) throws NoSuchAlgorithmException {
        EncodeUtil.userPasswordEncode(user);
        Integer integer = userService.addUser(user);
        redirect.addAttribute("uid", user.getUid());
        redirect.addAttribute("username", user.getUsername());
        log.info("{}", user);
        return "redirect:/success";
    }

    @GetMapping("/success")
    public String success(User user, Map<String, Object> map) {
        map.put("user", user);
        return "register_success";
    }

}
